package ai.assist.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import ai.assist.common.model.ExcelExportModel;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author hui
 * @Date 2021/7/29 下午12:49
 **/
public class ExcelUtils {

    private static Logger log = LoggerFactory.getLogger(ExcelUtils.class);

    /**
     * 导出Excel(07版.xlsx)到指定路径下
     *
     * @param path      路径
     * @param excelName Excel名称
     * @param sheetName sheet页名称
     * @param clazz     Excel要转换的类型
     * @param data      要导出的数据
     */
    public static void export2File(String path, String excelName, String sheetName, Class clazz, List data) {
        String fileName = path.concat(excelName).concat(ExcelTypeEnum.XLSX.getValue());
        EasyExcel.write(fileName, clazz).sheet(sheetName).doWrite(data);
    }

    /**
     * 导出Excel(07版.xlsx)到web
     *
     * @param response  响应
     * @param excelName Excel名称
     * @param sheetName sheet页名称
     * @param clazz     Excel要转换的类型
     * @param data      要导出的数据
     * @throws Exception
     */
    public static void export2Web(HttpServletResponse response, String excelName, String sheetName, Class clazz, List data) throws IOException {
        String fileName = URLEncoder.encode(excelName + ExcelTypeEnum.XLSX.getValue(), "UTF-8");
//        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        // 响应类型,编码
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 创建 ExcelWriter
//        ExcelWriterBuilder writerBuilder = new ExcelWriterBuilder();
//        ExcelWriter excelWriter = writerBuilder.excelType(ExcelTypeEnum.XLSX).file(response.getOutputStream()).build();
//
//        // 创建 Sheet
//        WriteSheet writeSheet = new WriteSheet();
//        writeSheet.setSheetName(sheetName);
//
//        // 写入数据到 Excel
//        excelWriter.write(data, writeSheet);
//
//        // 完成写入并关闭资源
//        excelWriter.finish();
//        response.setContentType("application/force-download");
//        response.addHeader("Access-Control-Expose-Headers", "Content-disposition");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
    }


    /**
     * 导出多个Sheet的Excel文件
     *
     * @param excelExportModel 导出模型
     */
    public static void exportWebMultiSheet(HttpServletResponse response, ExcelExportModel excelExportModel) throws IOException {
        String fileName = URLEncoder.encode(excelExportModel.getFileName() + DateUtilsEx.getStringDateTime2(new Date()) + ExcelTypeEnum.XLSX.getValue(), "UTF-8");
        List<ExcelExportModel.SheetInfo> sheetInfoList = excelExportModel.getSheetInfoList();
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        for (int i = 0; i < sheetInfoList.size(); i++) {
            ExcelExportModel.SheetInfo<?> sheetInfo = sheetInfoList.get(i);
            String sheetName = sheetInfo.getSheetName();
            List<?> dataList = sheetInfo.getDataList();
            Class clazz = sheetInfo.getClazz();
            WriteSheet sheet = EasyExcel.writerSheet(i, sheetName).head(clazz).build();
            excelWriter.write(dataList, sheet);
        }
        excelWriter.finish();
    }

    /**
     * 将指定位置指定名称的Excel导出到web
     *
     * @param response  响应
     * @param path      文件路径
     * @param excelName 文件名称
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String export2Web4File(HttpServletResponse response, String path, String excelName) throws UnsupportedEncodingException {
        File file = new File(path.concat(excelName).concat(ExcelTypeEnum.XLSX.getValue()));
        if (!file.exists()) {
            return "文件不存在！";
        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        excelName = URLEncoder.encode(excelName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + excelName + ExcelTypeEnum.XLSX.getValue());

        try (
                FileInputStream in = new FileInputStream(file);
                ServletOutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
            return "导出成功！";
        } catch (Exception e) {
            log.error("导出文件异常：", e);
        }

        return "导出失败！";
    }
}
